package com.example.fms.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.fms.constant.ChineseConstant;
import com.example.fms.constant.NumberConstant;
import com.example.fms.dto.req.AddMinOrderRuleReqDto;
import com.example.fms.dto.req.MinOrderRuleReqDto;
import com.example.fms.dto.resp.MinOrderRuleRespDto;
import com.example.fms.entity.MinOrderRule;
import com.example.fms.entity.StandardFreightRule;
import com.example.fms.enums.DeliveryTypeEnum;
import com.example.fms.exception.BusinessException;
import com.example.fms.exception.ExceptionEnum;
import com.example.fms.mapper.MinOrderRuleMapper;
import com.example.fms.service.MinOrderRuleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
public class MinOrderRuleServiceImpl extends ServiceImpl<MinOrderRuleMapper, MinOrderRule> implements MinOrderRuleService {

    @Resource
    private MinOrderRuleMapper minOrderRuleMapper;
    /**
     * 分页查询信息
     * @param req
     * @return
     */
    @Override
    public Page<MinOrderRuleRespDto > getMinOrderRuleList(MinOrderRuleReqDto req) {
        Page<MinOrderRuleRespDto > page = new Page<>(req.getPageNum(), req.getPageSize());
        List<MinOrderRuleRespDto> minOrderRuleList = minOrderRuleMapper.getMinOrderRuleList(page, req);
        if (CollectionUtil.isNotEmpty(minOrderRuleList)) {
            minOrderRuleList.forEach(s->{
                s.setType(DeliveryTypeEnum.getNameByCode(s.getType()));
            });
        }
        page.setRecords(minOrderRuleList);
        return page;
    }

    @Override
    public Boolean addMinOrderRule(AddMinOrderRuleReqDto req) {
        //创建qw
        LambdaQueryWrapper<MinOrderRule> qw = Wrappers.lambdaQuery();
        qw.eq(MinOrderRule::getWarehouse, req.getWarehouse())
                .eq(MinOrderRule::getProvince, req.getProvince())
                .eq(MinOrderRule::getType, req.getType());

        //查询有没有数据
        List<MinOrderRule> minOrderRulesProvinceArr = minOrderRuleMapper.selectList(qw);

        //如果没有直接插入
        if (minOrderRulesProvinceArr.isEmpty()) {
            save(req);
        } else {
            //有，执行相关逻辑
            //创建标记
            boolean cityResultEmpty = false;
            boolean districtResultEmpty = false;

            //校验市
            if (StrUtil.isNotEmpty(req.getCity())) {
                cityResultEmpty = checkRuleEmpty(req.getWarehouse(), req.getProvince(), req.getType(), req.getCity(), null,null);
            }

            //校验区
            if (!cityResultEmpty && StrUtil.isNotEmpty(req.getArea())) {
                districtResultEmpty = checkRuleEmpty(req.getWarehouse(), req.getProvince(), req.getType(), req.getCity(), req.getArea(),null);
            }

            //满足一个时候，通过
            if (cityResultEmpty || districtResultEmpty) {
                save(req);
            } else {
                throw new BusinessException(ExceptionEnum.MIN_CONFLICT_RULE);
            }
        }
        return true;
    }


    /**
     * 检查规则
     * @param warehouse
     * @param province
     * @param type
     * @param city
     * @param area
     * @return
     */
    private boolean checkRuleEmpty(String warehouse, String province, String type, String city, String area,Long id) {
        LambdaQueryWrapper<MinOrderRule> qw = Wrappers.lambdaQuery();
        if (id != null) {
            qw.ne(MinOrderRule::getId, id);
        }
        qw.eq(MinOrderRule::getWarehouse, warehouse)
                .eq(MinOrderRule::getProvince, province)
                .eq(MinOrderRule::getType, type)
                .in(MinOrderRule::getCity, city, ChineseConstant.NULL);

        if (StrUtil.isNotEmpty(area)) {
            qw.in(MinOrderRule::getArea, area,ChineseConstant.NULL);
        }

        List<MinOrderRule> result = minOrderRuleMapper.selectList(qw);
        return result.isEmpty();
    }

    @Override
    public Boolean deleteMinOrderRule(Long id) {
        int i = minOrderRuleMapper.deleteById(id);
        if (i == Integer.parseInt(NumberConstant.ZERO)) {
            throw new BusinessException(ExceptionEnum.DELETE_NUll);
        }
        return true;
    }

    @Override
    public Boolean upDateMinOrderRule(AddMinOrderRuleReqDto req) {
        if (req.getId() == null) {
            throw new BusinessException(ExceptionEnum.ID_ONT_NUll);
        }
        LambdaQueryWrapper<MinOrderRule> qw = Wrappers.lambdaQuery();
        //排除id相等的
        qw.ne(MinOrderRule::getId, req.getId())
                .eq(MinOrderRule::getWarehouse, req.getWarehouse())
                .eq(MinOrderRule::getProvince, req.getProvince())
                .eq(MinOrderRule::getType, req.getType());

        List<MinOrderRule> minOrderRulesProvinceArr = minOrderRuleMapper.selectList(qw);

        if (minOrderRulesProvinceArr.isEmpty()) {
            save(req);
        } else {
            //有，执行相关逻辑
            //创建标记
            boolean cityResultEmpty = false;
            boolean districtResultEmpty = false;

            //校验市
            if (StrUtil.isNotEmpty(req.getCity())) {
                cityResultEmpty = checkRuleEmpty(req.getWarehouse(), req.getProvince(), req.getType(), req.getCity(), null,null);
            }

            //校验区
            if (!cityResultEmpty && StrUtil.isNotEmpty(req.getArea())) {
                districtResultEmpty = checkRuleEmpty(req.getWarehouse(), req.getProvince(), req.getType(), req.getCity(), req.getArea(),null);
            }

            //满足一个时候，通过
            if (cityResultEmpty || districtResultEmpty) {
                save(req);
            } else {
                throw new BusinessException(ExceptionEnum.MIN_CONFLICT_RULE);
            }
        }
        return true;
    }

    /**
     * 修改或新增
     * @param req 操作数据
     */
    private void save(AddMinOrderRuleReqDto req) {
        if(StrUtil.isEmpty(req.getArea())) {
            req.setArea(ChineseConstant.NULL);
        }
        if(StrUtil.isEmpty(req.getCity())) {
            req.setCity(ChineseConstant.NULL);
        }
        LambdaQueryWrapper<MinOrderRule> dw = Wrappers.lambdaQuery();
        dw.eq(MinOrderRule::getRuleName, req.getRuleName())
                .ne(req.getId() != null, MinOrderRule::getId, req.getId());
        //规则名称校验
        List<MinOrderRule> minOrderRulesList = minOrderRuleMapper.selectList(dw);
        if (CollectionUtil.isNotEmpty(minOrderRulesList)) {
            throw new BusinessException(ExceptionEnum.MIN_CONFLICT_RULE_NAME);
        } else {
            MinOrderRule minOrderRule = new MinOrderRule();
            //将req复制到minOrderRule
            BeanUtils.copyProperties(req, minOrderRule);
            //插入
            if (req.getId() != null){
                log.info("修改规则:{}", minOrderRule);
                minOrderRuleMapper.updateById(minOrderRule);
            } else {
                log.info("插入规则:{}", minOrderRule);
                minOrderRuleMapper.insert(minOrderRule);
            }
        }
    }
}
